import React, { Component } from 'react'
import { Link, withRouter } from 'react-router-dom'
import { Menu, Icon } from 'antd'
import './index.less'
import logo from '../../assets/images/logo.png'
import menuList from '../../config/menuConfig'

const { SubMenu } = Menu

class LeftNav extends Component {
  constructor(props) {
    super(props)
    this.getCurrentReqParentPath(menuList, this.props.location.pathname)
  }
  // 根据导航json格式进行递归渲染
  // 方式一：map
  menuNav_map = menuConfig => {
    return menuConfig.map(item => {
      if (item.children) {
        return (
          <SubMenu
            key={item.key}
            title={
              <span>
                <Icon type={item.icon} />
                <span>{item.title}</span>
              </span>
            }
          >
            {this.menuNav_map(item.children)}
          </SubMenu>
        )
      } else {
        return (
          <Menu.Item key={item.key}>
            <Link to={item.key}>
              <Icon type={item.icon} />
              <span>{item.title}</span>
            </Link>
          </Menu.Item>
        )
      }
    })
  }

  //方式二：reduce
  menuNav_reduce = menuConfig => {
    return menuConfig.reduce((pre, item) => {
      if (item.children) {
        pre.push(
          <SubMenu
            key={item.key}
            title={
              <span>
                <Icon type={item.icon} />
                <span>{item.title}</span>
              </span>
            }
          >
            {this.menuNav_reduce(item.children)}
          </SubMenu>
        )
      } else {
        pre.push(
          <Menu.Item key={item.key}>
            <Link to={item.key}>
              <Icon type={item.icon} />
              <span>{item.title}</span>
            </Link>
          </Menu.Item>
        )
      }

      return pre
    }, [])
  }

  //保持选中状态（若选择的是二级菜单，一级菜单需要展开）
  getCurrentReqParentPath = (arr, getCurrentReqPath) => {
    arr.forEach(element => {
      if (element.children) {
        element.children.forEach(cItem => {
          if (getCurrentReqPath.includes(cItem.key)) {
            // 得到需要展开的key
            this.currentReqParentPath = element.key
          }
        })
      }
    })
  }

  render() {
    // 获取当前页面的pathname,如果不是路由组件，需要经过withRouter的包装
    let getCurrentReqPath = this.props.location.pathname
    // 当前路径对应的一级菜单项
    const currentReqParentPath = this.currentReqParentPath

    return (
      <div className="left-nav">
        <Link to="/home" className="left-nav-header">
          <img src={logo} alt="logo" />
          <h1>管理后台</h1>
        </Link>

        <Menu
          mode="inline"
          theme="dark"
          selectedKeys={[getCurrentReqPath]}
          defaultOpenKeys={[currentReqParentPath]}
        >
          {this.menuNav_reduce(menuList)}
        </Menu>
      </div>
    )
  }
}

export default withRouter(LeftNav)
